import '../../../public.dart';

/// 弹幕服务类
///
class ReaderBarrageService {
  ReaderBarrageService();

  /// 获取弹幕
  Future<List<ChapterBarrageModel>> getChapterBarrage(
      ChapterModel chapter) async {
    List<dynamic> re = await ACGN.http
        .fetch(ACGN.config.interfaceApi.receiveDanmu, queryParameters: {
      'comic_id': chapter.comicModel.id,
      'sourceId':
          chapter.comicModel.id.toString() + '_' + chapter.id.toString(),
      'order': 2, // 倒序 ，start和end也要倒着来
      'startPageId': chapter.totalPage,
      'endPageId': 1,
      'chapter_id': 'chapter_id'
    });
    if (re == null || re.length == 0) {
      return [];
    }

    List<ChapterBarrageModel> lst = [];
    re.forEach((item) {
      int pageIndex = item['pageId'];
      List<dynamic> data = item['data'];
      data.forEach((ele) {
        lst.add(ChapterBarrageModel.fromData(ele, pageIndex, chapter));
      });
    });
    return lst;
  }

  /// 提交弹幕
  Future<bool> addBarrage(ChapterBarrageModel chapterBarrageModel) async {
    var re = await ACGN.http.fetch(ACGN.config.interfaceApi.sendDanmu,
        method: HttpMethodType.POST,
        hasStatus: true,
        data: {
          "sourceId": chapterBarrageModel.comicId.toString() +
              '_' +
              chapterBarrageModel.chapterId.toString(),
          "timeStamp": DateTime.now().millisecondsSinceEpoch,
          "msg": chapterBarrageModel.text,
          "uId": chapterBarrageModel.uId,
          "pageId": chapterBarrageModel.imageIndex,
          "fontColor": chapterBarrageModel.fontColor, // 传入值没有#号
          "isVIP": chapterBarrageModel.isVIP
        });
    var flag = re['status'] == 1;
    ACGN.toast.message(!flag ? re['msg'] : '发送成功');
    return flag;
  }
}
